package com.hd.appcommon.utils;

import com.alibaba.fastjson.JSONObject;
import com.hd.appcommon.constant.Constant;
import com.hd.appcommon.utils.HttpClientUtils;
import com.hd.hdxgddcommon.utils.HttpUtils;
import com.hd.hdxgddcommon.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HzieeAPIUtils {

    private static String HZIEE_API_IP = "http://10.130.5.199:31704";
    private static String HZIEE_API_STU_SCORES = HZIEE_API_IP + "/cec-data-manage-api/dpTestScores/getStuScoresList";
    private static String HZIEE_API_COURSE_ARRANGEMENT = HZIEE_API_IP + "/cec-data-manage-api/dpCourseArrangement/getCourseArrangeMsg";


    @Autowired
    RedisTemplate redisTemplate;

    //请求排课信息
    public JSONObject requestCourseArrangement(String year, String term, Integer page, Integer size){
        Map<String, String> map = new HashMap<>();
        if (year != null) {
            map.put("KKXND", year.toString());
        }
        if (term != null) {
            map.put("KKXQM", term.toString());
        }

        return requestHzieeAPI(HZIEE_API_COURSE_ARRANGEMENT, map, page, size,"get");
    }



    //请求学生成绩接口
    public JSONObject requestCourseScores(String sno, String year, String term, Integer page, Integer size) {

        Map<String, String> map = new HashMap<>();
        map.put("XH", sno);
        if (year != null) {
            map.put("XN", year.toString());
        }
        if (term != null) {
            map.put("XQM", term.toString());
        }

        return requestHzieeAPI(HZIEE_API_STU_SCORES, map, page, size);
    }

    //获取token
    public String getToken() {

        String access_token = (String) redisTemplate.opsForValue().get("school_token");
        if (access_token == null) {
            Map<String, Object> param = new HashMap<>();
            param.put("appKey", Constant.SCHOOL_APP_KEY);
            param.put("appSecret", Constant.SCHOOL_APP_SECRET);
            CloseableHttpResponse response = null;
            HttpEntity entity = null;
            Map<String, Object> map = new HashMap<>();
            try {
                response = HttpUtils.doGet("http://10.130.5.199:31704/auth/get_token", param);
                if (response != null) {
                    entity = response.getEntity();
                    map = JsonUtil.JsonStrToMap(EntityUtils.toString(entity));
                    access_token = JsonUtil.JsonStrToMap(map.get("data").toString()).get("access_token").toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (access_token != null) {
                redisTemplate.opsForValue().set("school_token", access_token, 7200, TimeUnit.SECONDS);
            }
        }
        return access_token;
    }

    //请求信工api
    public JSONObject requestHzieeAPI(String url, Map<String,String> params, Integer page, Integer size, String method) {

        String access_token = getToken();

        params.put("page", page.toString());
        params.put("size", size.toString());

        String postUrl = url;
        if (method.equals("post")){
            postUrl = url + "?access_token=" + access_token;
        }else{
            params.put("access_token",access_token);
        }


        String res = null;
        JSONObject body = null;


        try {
            if (method.equals("post")){
                res = HttpClientUtils.post(postUrl, params);
            }else{
                res = HttpClientUtils.get(postUrl, params);
            }
            body = JSONObject.parseObject(res);
        } catch (SocketTimeoutException e) {
            log.error(e.getMessage());
            log.error("请求接口超时,重发请求。url：{}",url);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException interruptedException) {
                log.error("do something error: ", interruptedException);
            }
            return requestHzieeAPI(url, params,page,size,method);
        } catch (Exception e) {
            log.error(res);
            e.printStackTrace();
            log.error(e.getMessage());
            return null;
        }

        if (!body.getString("success").equals("true")) {
            log.error(res);
            return null;
        }
        return body.getJSONObject("data");
    }

    public JSONObject requestHzieeAPI(String url, Map<String,String> params, Integer page, Integer size ) {
        return requestHzieeAPI(url, params, page, size, "post");
    }
}
